package com.wocai.jrt.orgadmin.riskEvaluation.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.wocai.jrt.orgadmin.investor.model.Investor;
import com.wocai.jrt.orgadmin.investor.service.spi.InvestorService;
import com.wocai.jrt.orgadmin.riskEvaluation.bean.QuestionDetailBean;
import com.wocai.jrt.orgadmin.riskEvaluation.dao.QuestionDao;
import com.wocai.jrt.orgadmin.riskEvaluation.model.Answer;
import com.wocai.jrt.orgadmin.riskEvaluation.model.Options;
import com.wocai.jrt.orgadmin.riskEvaluation.model.Paper;
import com.wocai.jrt.orgadmin.riskEvaluation.model.Question;
import com.wocai.jrt.orgadmin.riskEvaluation.model.QuestionBean;
import com.wocai.jrt.orgadmin.riskEvaluation.service.spi.AnswerService;
import com.wocai.jrt.orgadmin.riskEvaluation.service.spi.OptionsService;
import com.wocai.jrt.orgadmin.riskEvaluation.service.spi.PaperService;
import com.wocai.jrt.orgadmin.riskEvaluation.service.spi.QuestionService;
import com.lowagie.text.pdf.BaseFont;
import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.utils.common.PropsUtils;

/**
 * 题库题目相关的service业务实现。
 * @author yinlei
 * @date 2015-10-28 16:03:03
 */
@Named
public class QuestionServiceImpl extends MyBatisServiceImpl<Question, QuestionBean, String> implements QuestionService {
	// 添加了方法后，记得改为private
	protected QuestionDao questionDao;
	@Inject
	private AnswerService answerServiceImpl;
	@Inject
	private InvestorService investorServiceImpl;
	@Inject
	private PaperService paperServiceImpl;
	@Inject
	private OptionsService optionsServiceImpl;
	public static final String FILE_PATH = PropsUtils.get("file.path")+"evaluafile/";
	
	private static final Logger LOGGER = LoggerFactory.getLogger(QuestionServiceImpl.class);
	@Override
	@Inject
	public void setBaseDao(BaseDao<Question, QuestionBean, String> questionDao) {
		this.baseDao = questionDao;
		this.questionDao = (QuestionDao) questionDao;
	}

	@Override
	public Map<String, Object>  getEvulaDetail(String id) {
		Map<String, Object> maps = new HashMap<String, Object>();
		Answer answer = new Answer();
		answer.setInvestorId(id);
		List<Answer> ansList = answerServiceImpl.pagedList(answer);
		Map<String, Answer> ansMaps = new HashMap<String, Answer>();
		for (Answer ans : ansList) {
			ansMaps.put(ans.getQuestionId(), ans);
		}
		Investor investor = investorServiceImpl.get(id);
		if (ansList.size() > 0) {
			Paper p = new Paper();
			p = paperServiceImpl.get(ansList.get(0).getPaperId());
			// 获取试题列表
			Question ques = new Question();
			ques.setPaperId(ansList.get(0).getPaperId());
			ques.setOrderBy("no asc");
			List<Question> quesList = questionDao.pagedList(ques);
			List<QuestionDetailBean> quesDetailList = new ArrayList<QuestionDetailBean>();
			for (Question question : quesList) {
				QuestionDetailBean tempBean = new QuestionDetailBean();
				Answer tempAns = ansMaps.get(question.getId());
				String ansStr = "";
				if(tempAns !=null && tempAns.getAnswerOption() != null){
					ansStr = tempAns.getAnswerOption();
				}
				question.setAnswer(ansStr);
				tempBean.setQuestion(question);
				Options opt = new Options();
				opt.setQuestionId(question.getId());
				opt.setOrderBy("no asc");
				List<Options> optList = optionsServiceImpl.pagedList(opt);
				for (Options options : optList) {
					tempBean.addOptions(options);
				}
				quesDetailList.add(tempBean);
			}
			maps.put("quesDetailList", quesDetailList);
			maps.put("paperName", p);
			maps.put("investor", investor);
		}
		return maps;
	}

	@Override
	public List<Question> queryMyList(Question model) {
		return questionDao.queryMyList(model);
	}
	
	/**
	 * 投资人测评脚本,为已测评但未生成测评结果pdf投资人生成测评结果
	 */
	@Override
	public int investorScript() {
		int ii= 0;
		Investor i = new Investor();
		List<Investor> list = investorServiceImpl.pagedList(i);
		for (Investor investor : list) {
			//测评状态不是未测评状态且测评签字确认图片不为空
			if (investor.getEvaluaState() != 3 && !StringUtils.isBlank(investor.getSignImage())) {
				createEvaluationPDF(investor.getId());
				investor.setEvaluaFile(FILE_PATH+investor.getId()+"/"+investor.getId()+".pdf");
				investorServiceImpl.updateById(investor);
				ii++;
			}
		}
		return ii;
	}
	
	/**
	 * 生成投资人测评结果pdf
	 * @param id
	 */
	public void createEvaluationPDF(String id){
		String outputFile = "";
		PropsUtils.get("file.path");
		try {
			//获取试卷、投资人信息、测评结果信息
			Map<String, Object> map = this.getEvulaDetail(id);
			Investor investor = (Investor) map.get("investor");
			String imagesPrefix = PropsUtils.get("images.prefix");
			String idCard = "-";
			if(!StringUtils.isBlank(investor.getIdcard())){
				idCard = investor.getIdcard();
			}
			@SuppressWarnings("unchecked")
			List<QuestionDetailBean> quesDetailList = (List<QuestionDetailBean>) map.get("quesDetailList");
			// 拼接测评试卷结果html
			String html = "<div id=\"paper_content\" class=\"tab-content\">"
					+ "<div class=\"tab-pane active\">"
					+ "<div class=\"panel-body\">"
					+ "<div class=\"wrapper wrapper-content animated fadeInRight ecommerce\">"
					+ "<div class=\"row\">"
					+ "<div class=\"col-lg-12\">"
					+ "<center>"
					+ "<label class=\"control-label\"  style=\"font-size:18pt;\">试卷名称: "
					+ "投资者尽职调查问卷"
					+ "</label><br/><br/>"
					+ "<label class=\"control-label\"  style=\"margin-left:0px;\">测评人:"
					+ investor.getName()
					+ "</label>"
					+ "<label class=\"control-label\" style=\"margin-left:20px;\">&nbsp;&nbsp;&nbsp;证件号码:"
					+ idCard
					+ "</label>"
					+ "<br/><label class=\"control-label\" style=\"margin-left:20px;\">&nbsp;&nbsp;&nbsp;测评时间: "
					+ DateFormatUtils.format(investor.getEvaluationTime(), "yyyy-MM-dd")
					+ "</label>"
					+ "<label class=\"control-label\" style=\"margin-left:20px;\">&nbsp;&nbsp;&nbsp;得分: "
					+ investor.getScore()
					+ "分</label>"
					+ "&nbsp;&nbsp;&nbsp;";
			if (investor.getRiskPass()) {
				html = html
						+ "<label style=\"font-size:20pt;color:red;margin-left:40px;\">通过</label>";
			} else {
				html = html
						+ "<label style=\"font-size:20pt;color:red;margin-left:40px;\">未通过</label>";
			}
			html = html
					+ "</center><br/><div class=\"ibox float-e-margins\"><div class=\"ibox-content\">";
			for (QuestionDetailBean quesList : quesDetailList) {
				html = html + "<tr><td align = \"center\" ><label style=\"font-size:13pt;\">"
						+ quesList.getQuestion().getNo() + "、</label></td>"
						+ "<td align = \"center\" ><label style=\"font-size:13pt;\">"
						+ quesList.getQuestion().getTitle() + "</label></td></tr><br/>";
				for (Options quesOpts : quesList.getOptList()) {
					html = html
							+ "&nbsp;&nbsp;&nbsp;<tr><td align = \"center\">"
							+ quesOpts.getNo()
							+ ".</td><td align = \"center\">"
							+ quesOpts.getContent()
							+ "</td>"
							+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<td align = \"center\" style=\"margin-left:50px;\">"
							+ quesOpts.getScore() + "分</td></tr>";
				}
				html = html + "&nbsp;&nbsp;&nbsp;&nbsp;<td align = \"center\">";
				html = html + "<br/>测评人答案:";
				if (quesList.getQuestion().getAnswer() == null
						|| quesList.getQuestion().getAnswer().equals("")) {
					html = html + "无";
				} else {
					html = html + quesList.getQuestion().getAnswer();
				}
				html = html + "</td><br/><br/>";
			}
			html = html + "<label class=\"control-label\"  style=\"font-size:14pt;\">投资人签名确认:</label><br/>";
			html = html + "<img alt=\"理财师签字\" style=\"width:200px;height:150px;\" src=\""+imagesPrefix+investor.getSignImage()+"\"></img>";
			html = html + "</div></div></div></div></div></div></div></div>";
			//如果文件夹不存在,则生成文件夹
			File _file = new File(FILE_PATH);
			if (!_file.exists()) {
				_file.mkdir();
			}
			File _fileParent = new File(FILE_PATH+id);
			if (!_fileParent.exists()) {
				_fileParent.mkdir();
			}
			outputFile =FILE_PATH+id+"/"+id+".pdf";
			File f = new File(outputFile);
			// 如果文件不存在则创建文件
			if (!f.exists()) {
				f.createNewFile();
			}
			OutputStream os = new FileOutputStream(outputFile);
			ITextRenderer renderer = new ITextRenderer();
			// 解决中文支持问题
			ITextFontResolver fontResolver = renderer.getFontResolver();
			fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H,
					BaseFont.NOT_EMBEDDED);
			StringBuffer htmlStr = new StringBuffer();
			// 添加html头文件以免中文加载出错
			htmlStr.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
			htmlStr.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">")
					.append("<head>")
					.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
					.append("<style type=\"text/css\" mce_bogus=\"1\">body {font-family: SimSun;}</style>")
					.append("</head>").append("<body>");
			htmlStr.append(html);
			htmlStr.append("</body></html>");
			renderer.setDocumentFromString(htmlStr.toString());
			// 解决图片的相对路径问题
			renderer.getSharedContext().setBaseURL("file:/c:/");
			renderer.layout();
			//讲pdf文件写入流中
			renderer.createPDF(os);
    		os.close();
		} catch (Exception e) {
			LOGGER.error("createEvaluationPDF error due to [{}]",e.getMessage());
		} 
	}
}
